package com.ruoyi.web.controller.lucky;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SnDrawConfig;
import com.ruoyi.system.domain.SnUserLib;
import com.ruoyi.system.service.ISnDrawConfigService;
import com.ruoyi.system.service.ISnUserLibService;
import com.ruoyi.web.config.LuckConfig;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.List;

/**
 * 彩民抽奖信息库Controller
 *
 * @author ruoyi
 * @date 2022-12-26
 */
@Controller
@RequestMapping("/system/lucky")
public class SnUserLibController extends BaseController {
    private Logger LOGGER = LoggerFactory.getLogger(SnUserLibController.class);
    private String prefix = "system/lucky";

    @Autowired
    private LuckConfig luckConfig;

    @Autowired
    private ISnUserLibService snUserLibService;

    @Autowired
    private ISnDrawConfigService snDrawConfigService;

    @RequiresPermissions("system:lucky:view")
    @GetMapping()
    public String lib(ModelMap mmap) {
        mmap.put("luckyHtmlUrl", luckConfig.getLuckyHtmlUrl());//抽奖页面调用地址
        return prefix + "/lib";
    }

    /**
     * 查询彩民抽奖信息库列表
     */
    @RequiresPermissions("system:lucky:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SnUserLib snUserLib) {
        startPage();
        List<SnUserLib> list = snUserLibService.selectSnUserLibList(snUserLib);
        return getDataTable(list);
    }

    /**
     * 导出彩民抽奖信息库列表
     */
    @RequiresPermissions("system:lucky:export")
    @Log(title = "彩民抽奖信息库", businessType = BusinessType.EXPORT)
    @PostMapping("/exportData")
    @ResponseBody
    public AjaxResult exportData(SnUserLib snUserLib) {
        List<SnDrawConfig> drawConfigs = snDrawConfigService.getCurrentConfig();
        if (drawConfigs.size() == 0) {
            return AjaxResult.error("当前日期不为抽奖日期,无抽奖结果导出");
        }
        SnDrawConfig snDrawConfig = drawConfigs.stream().findFirst().get();
        snUserLib.setLucky(1);
        snUserLib.setTermNo(snDrawConfig.getTermNo());
        List<SnUserLib> list = snUserLibService.selectSnUserLibList(snUserLib);
        if (list.size() == 0) {
            return AjaxResult.error("当前无抽奖结果数据");
        }
        ExcelUtil<SnUserLib> util = new ExcelUtil<SnUserLib>(SnUserLib.class);
        String sheetName = "第".concat(snDrawConfig.getTermNo()).concat("期抽奖结果");
        String title = "陕西福彩生肖活动第".concat(snDrawConfig.getTermNo()).concat("期抽奖结果");
        return util.exportExcel(list, sheetName, title);
    }

    /**
     * 新增彩民抽奖信息库
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存彩民抽奖信息库
     */
    @RequiresPermissions("system:lucky:add")
    @Log(title = "彩民抽奖信息库", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SnUserLib snUserLib) {
        // snUserLib.setId(RandomStringUtils.randomAlphanumeric(20, 20));
        List<SnDrawConfig> drawConfigs = snDrawConfigService.getCurrentConfig();
        if (drawConfigs.size() == 0) {
            return AjaxResult.error("当前日期不为抽奖日期");
        }
        SnDrawConfig snDrawConfig = drawConfigs.stream().findFirst().get();
        snUserLib.setTermNo(snDrawConfig.getTermNo());
        return toAjax(snUserLibService.insertSnUserLib(snUserLib));
    }

    /**
     * 清空彩民抽奖信息库
     */
    @RequiresPermissions("system:lucky:clear")
    @Log(title = "彩民抽奖信息库", businessType = BusinessType.DELETE)
    @PostMapping("/clear")
    @ResponseBody
    public AjaxResult clear() {
        snUserLibService.deleteSnUserLib();
        return toAjax(true);
    }

    /**
     * 删除彩民抽奖信息库
     */
    @RequiresPermissions("system:lucky:remove")
    @Log(title = "彩民抽奖信息库", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(snUserLibService.deleteSnUserLibByIds(ids));
    }


    /**
     * 下载模板
     */
    @RequiresPermissions("system:lucky:export")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<SnUserLib> util = new ExcelUtil<SnUserLib>(SnUserLib.class);
        return util.importTemplateExcel("彩民数据");
    }

    /**
     * 导入数据
     */
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file) throws Exception {
        List<SnDrawConfig> drawConfigs = snDrawConfigService.getCurrentConfig();
        if (drawConfigs.size() == 0) {
            return AjaxResult.error("当前日期不为抽奖日期");
        }
        SnDrawConfig snDrawConfig = drawConfigs.stream().findFirst().get();
        String termNo = snDrawConfig.getTermNo();

        //解析Excel中全部彩民信息
        ExcelUtil<SnUserLib> util = new ExcelUtil<SnUserLib>(SnUserLib.class);
        List<SnUserLib> userList = util.importExcel(file.getInputStream());
        LOGGER.info("导入用户总数量===" + userList.size());
        //补充彩民信息(随机ID、抽奖期号)
        userList.stream().forEach($ -> {
            // $.setId(RandomStringUtils.randomAlphanumeric(20, 20));
            $.setTermNo(termNo);
        });
        //随机打乱进行保存
        Collections.shuffle(userList);
        try {
            //大批量彩民，拆分成小集合，多线程进行入库保存，减少耗时
            int result = snUserLibService.batchSaveSnUserLib(userList);
            //汇总各线程执行成功结果
            String message = result + " 条彩民信息导入成功";
            return AjaxResult.success(message);
        } catch (Exception ex) {
            snUserLibService.deleteSnUserLib();
            String message = " 彩民信息导入发生异常，请稍后重试";
            return AjaxResult.error(message);
        }
    }

}
